<template>
  <div>
    <el-form :model="bookQueryForm" inline ref="queryRef">
      <el-form-item label="关键字" prop="keyword">
        <el-input v-model="bookQueryForm.keyword"></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-tree-select
            v-model="bookQueryForm.categoryId"
            :data="parentCategoryList"
            check-strictly
            :props="props"
            node-key="categoryId"
            :render-after-expand="false"
            style="width: 240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getBookPage" icon="Search">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="queryRef.resetFields()" icon="Refresh">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" size="small" icon="Plus" @click="dialogVisible=true" v-permission="'book:create'">新增</el-button>
    <excel-export-button url="/book/export" title="图书列表"></excel-export-button>
    <excel-import-button  url="/book/import"></excel-import-button>
    <el-table :data="bookPage.list" v-loading="loading">
      <el-table-column label="封面">
        <template #default="scoped">
          <el-icon size="40">
            <el-image :src="scoped.row.cover"/>
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="bookId" label="图书ID"></el-table-column>
      <el-table-column prop="isbn" label="ISBN"></el-table-column>
      <el-table-column prop="title" label="图书名称"></el-table-column>
      <el-table-column prop="subtitle" label="副标题"></el-table-column>
      <el-table-column prop="author" label="作者"></el-table-column>
      <el-table-column prop="publisher" label="出版社"></el-table-column>
      <el-table-column label="出版日期">
        <template #default="scoped">
          {{ $timeFormat(scoped.row.publishDate, 'yyyy-mm-dd') }}
        </template>
      </el-table-column>
      <el-table-column prop="price" label="定价"></el-table-column>
      <el-table-column prop="pages" label="页数"></el-table-column>
      <el-table-column prop="edition" label="版次"></el-table-column>
      <el-table-column prop="location" label="图书位置"></el-table-column>
      <el-table-column prop="status" label="状态"></el-table-column>
      <el-table-column prop="categoryId" label="分类ID"></el-table-column>
      <el-table-column prop="stock" label="库存"></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="warning" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex-end">
      <el-pagination
          background
          layout="prev, pager, next"
          :total="bookPage.total"
          v-model:page-size="bookQueryForm.pageSize"
          v-model:current-page="bookQueryForm.pageNum"
      >
      </el-pagination>
    </div>
    <el-dialog
        v-model="dialogVisible"
        :title="isAdd ? '新增图书' : '修改图书' "
        width="800"
        @close="closeHandel"
    >
      <el-form :model="bookSaveForm" label-width="120px" inline ref="bookSaveFormRef" :rules="rules">
        <el-form-item label="封面" prop="cover">
          <el-upload
              class="avatar-uploader"
              :action="bookCoverUploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              accept="image/*"
          >
            <img v-if="bookSaveForm.cover " :src="bookSaveForm.cover " class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="唯一编号" prop="isbn">
          <el-input v-model="bookSaveForm.isbn"></el-input>
        </el-form-item>
        <el-form-item label="定价" prop="price">
          <el-input v-model="bookSaveForm.price"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="bookSaveForm.author"></el-input>
        </el-form-item>
        <el-form-item label="图书名称" prop="title">
          <el-input v-model="bookSaveForm.title"></el-input>
        </el-form-item>
        <el-form-item label="副标题" prop="subtitle">
          <el-input v-model="bookSaveForm.subtitle"></el-input>
        </el-form-item>
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="bookSaveForm.publisher"></el-input>
        </el-form-item>
        <el-form-item label="出版日期" prop="publishDate">
          <el-date-picker
              v-model="bookSaveForm.publishDate"
              type="date"
              placeholder="选择出版日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="图书位置" prop="location">
          <el-input v-model="bookSaveForm.location"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-input v-model="bookSaveForm.status"></el-input>
        </el-form-item>
        <el-form-item label="页数" prop="pages">
          <el-input-number v-model="bookSaveForm.pages"></el-input-number>
        </el-form-item>
        <el-form-item label="版次" prop="edition">
          <el-input-number v-model="bookSaveForm.edition"></el-input-number>
        </el-form-item>
        <el-form-item label="关联分类" prop="categoryId">
          <el-cascader v-model="bookSaveForm.categoryId" :options="bookCategoryList" :show-all-levels="false"
                       :props="categoryProps"/>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="bookSaveForm.stock"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSaveBook(bookSaveFormRef)">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from "vue";
import {reqCreateBook, reqExportBook, reqGetBookPageList, reqUpdateBook} from "@/api/book/index.js";
import {reqGetBookCategoryTreeList} from "@/api/book/bookCategory.js";
import {bookCoverUploadUrl} from '@/util/uploade.js'


let bookQueryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  author: '',
  publisher: '',
  categoryId: ''
})
let bookSaveForm = reactive({
  bookId: null,
  isbn: "",
  price: null,
  author: "",
  title: "",
  subtitle: "",
  publisher: "",
  publishDate: null,
  location: "",
  status: "",
  pages: null,
  edition: null,
  categoryId: null,
  stock: 0
})
let bookSaveFormRef = ref()
let bookCategoryList = ref([])
let dialogVisible = ref(false)
let parentCategoryList = ref([])
let queryRef = ref()
let loading = ref(true)
let bookPage = reactive({
  pageNum: 1,
  list: [],
  total: 0
})
let isAdd = ref(true)
let props = reactive({
  label: 'name',
  children: 'children'
})
let categoryProps = reactive({
  value: 'categoryId',
  label: 'name',
  children: 'children',
  emitPath: false
})
const handleAvatarSuccess = (response, file, fileList) => {
  if (response) {
    bookSaveForm.cover = response; // 将上传后的URL保存到表单中
  }
};

let getBookCategoryList = async () => {
  let res = await reqGetBookCategoryTreeList()
  bookCategoryList.value = res.data
  parentCategoryList.value = [{
    categoryId: 0,
    name: '顶级分类',
    children: res.data
  }]
}
let getBookPage = () => {
  reqGetBookPageList(bookQueryForm).then((res) => {
    Object.assign(bookPage, res.data)
    loading.value = false
  })
}
let handleEdit = (node) => {
  Object.assign(bookSaveForm, node)
  isAdd.value = false
  dialogVisible.value = true
}
//重置
let closeHandel = () => {
  Object.assign(bookSaveForm, {
    bookId: null,
    isbn: "",
    price: null,
    author: "",
    title: "",
    subtitle: "",
    publisher: "",
    publishDate: null,
    location: "",
    status: "",
    pages: null,
    edition: null,
    categoryId: null,
    stock: 0
  })
  isAdd.value = true
}
let submitSaveBook = async (formEl) => {
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (isAdd.value) {
        await reqCreateBook(bookSaveForm)
      } else {
        console.log("修改")
        await reqUpdateBook(bookSaveForm)
      }
      await getBookPage()
      dialogVisible.value = false
    } else {
      console.log('error submit!', fields)
    }
  })

}

onMounted(() => {
  getBookPage()
  getBookCategoryList()
})

watch([() => bookQueryForm.pageNum, () => bookQueryForm.pageSize], () => {
  getBookPage()
})
let rules = {
  isbn: [
    {required: true, message: '请输入唯一编号', trigger: 'blur'},
    {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
  ],
  price: [
    {required: true, message: '请输入定价', trigger: 'blur'},
  ],
  author: [
    {required: true, message: '请输入作者', trigger: 'blur'},
    {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
  ],
  title: [
    {required: true, message: '请输入图书名称', trigger: 'blur'},
    {min: 1, max: 50, message: '长度在 1 到 20 个字符', trigger: 'blur'}
  ]
  ,
  subtitle: [
    {required: true, message: '请输入副标题', trigger: 'blur'},
    {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
  ],
  publisher: [
    {required: true, message: '请输入出版社', trigger: 'blur'},
    {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
  ],
  publishDate: [
    {required: true, message: '请输入出版日期', trigger: 'blur'},
  ]
  ,
  location: [
    {required: true, message: '请输入图书位置', trigger: 'blur'},
    {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
  ],
  status: [
    {required: true, message: '请输入状态', trigger: 'blur'},
  ],
  pages: [
    {required: true, message: '请输入页数', trigger: 'blur'},
  ],
  edition: [
    {required: true, message: '请输入版次', trigger: 'blur'},
  ],
  categoryId: [
    {required: true, message: '请输入分类id', trigger: 'blur'},
  ],
  stock: [
    {required: true, message: '请输入库存', trigger: 'blur'},
  ]
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
